package org.jjche.sys.modules.system.rule;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.jjche.common.util.StrUtil;
import org.jjche.core.handler.IFillRuleHandler;
import org.jjche.sys.modules.system.domain.DeptDO;
import org.jjche.sys.modules.system.service.DeptService;

import java.util.Map;

/**
 * <p>
 * 部门编码生成规则
 * </p>
 *
 * @author miaoyj
 * @since 2024-05-15
 */
public class SysDeptCodeRule implements IFillRuleHandler {
    /**
     * 父级
     */
    public static final String PARAM_PID = "pid";
    /**
     * 前缀
     */
    private final String PARAM_PREFIX = "prefix";
    /**
     * 数字长度
     */
    private final String PARAM_NUM_LENGTH = "num_length";

    @Override
    public String execute(Map<String, Object> params, Map<String, Object> formData) {
        DeptService deptService = SpringUtil.getBean(DeptService.class);
        //数字长度
        Integer numLength = null;
        //前缀
        String prefix = null;
        //父id
        String pid = null;
        //父id优先取formData
        if (formData != null && formData.size() > 0) {
            pid = MapUtil.getStr(formData, PARAM_PID);
        }
        if (params != null) {
            if (formData != null && !formData.containsKey(PARAM_PID)) {
                pid = MapUtil.getStr(params, PARAM_PID);;
            }
            prefix = MapUtil.getStr(params, PARAM_PREFIX);
            numLength = MapUtil.getInt(params, PARAM_NUM_LENGTH);
        }
        DeptDO deptDO = deptService.getMaxCodeDept(pid);
        String oldCodeStr = prefix + "0";
        if (deptDO != null) {
            oldCodeStr = deptDO.getCode();
        }
        //截取数字 A01A02 -> 02
        String oldCodeNumber = StrUtil.subAfter(oldCodeStr, prefix, true);
        //自增+1 02 -> 03
        Integer oldCodeNumberPlus = NumberUtil.parseInt(oldCodeNumber) + 1;
        //拼接前缀 03 -> A03
        String newCode = prefix + String.format("%0" + numLength + "d", oldCodeNumberPlus);
        //获取A01
        String newCodePlusStr = StrUtil.subBefore(oldCodeStr, prefix, true);
        //拼接 A01A03
        return newCodePlusStr + newCode;
    }
}
